//
//  CLCustomButton.m
//  Charles
//
//  Created by Charles on 2019/7/6.
//  Copyright © 2019 charles. All rights reserved.
//

#import "CLCustomButton.h"

@implementation CLCustomButton

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"CLCustomButton Touched!!");
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    NSLog(@"*****************%@",NSStringFromClass(self.class));
    if (self.alpha < 0.01 || !self.userInteractionEnabled || self.isHidden) {
        return nil;
    }
    if ([self pointInside:point withEvent:event]) {
        // 遍历当前对象的子视图
        __block UIView *hit = nil;
        [self.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"----%@",NSStringFromClass(obj.class));
            // 坐标转换
            CGPoint convertPoint = [self convertPoint:point toView:obj];
            // 调用子视图的hittest方法
            hit = [obj hitTest:convertPoint withEvent:event];
            // 如果找到了接受时间的对象，则s停止遍历
            if (hit) {
                *stop = YES;
            }
        }];
        if (hit) {
            return hit;
        }else {
            return self;
        }
    }else {
        return nil;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat x1 = point.x;
    CGFloat y1 = point.y;
    
    CGFloat x2 = self.frame.size.width / 2;
    CGFloat y2 = self.frame.size.height / 2;
    
    double dis = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    if (dis <= self.frame.size.width / 2) {
        return YES;
    }else {
        return NO;
    }
}


@end
